#!/bin/bash

function error {
  echo -e "\e[91m$1\e[39m"
  exit 1
}

cd $HOME

if [[ "$(id -u)" == 0 ]]; then
	error "Pi-Apps is not designed to be installed as root! Please try again as a regular user."
fi

command -v apt >/dev/null || error "apt: command not found. Most likely this system is not running Debian."
#Ensure running arm processor
if uname -m | grep -q 'x86' ;then
  error "Pi-Apps is not not supported on non-arm processor architectures like amd64 and i386. You may be interested in Pi-Apps x86, a unofficial fork of Pi-Apps for x64 and x86 systems: https://github.com/Pi-Apps-Recreates/pi-apps-x86"
fi

sudo apt update || error "The command 'sudo apt update' failed. Before Pi-Apps will work, you must fix your apt package-management system."

#install yad automatically
if ! command -v yad >/dev/null;then
  sudo apt install -y yad || error "Failed to install yad."
fi
#remove annoying YAD icon browser launcher
sudo rm -f /usr/share/applications/yad-icon-browser.desktop

#install git
if ! command -v git >/dev/null;then
  sudo apt install -y git || error "Failed to install git."
fi

#install curl
if ! command -v curl >/dev/null;then
  sudo apt install -y curl || error "Failed to install curl."
fi

#download pi-apps if folder missing
DIRECTORY="$(readlink -f "$(dirname "$0")")"
if [ -z "$DIRECTORY" ] || [ "$DIRECTORY" == "$HOME" ] || [ "$DIRECTORY" == bash ];then
  DIRECTORY="$HOME/pi-apps"
  
  #if directory does not exist, download it
  if [ ! -d "$DIRECTORY" ];then
    echo "Downloading Pi-Apps..."
    output="$(git clone --depth 1 https://github.com/Botspot/pi-apps "$DIRECTORY" 2>&1)"
    if [ ! -d "$DIRECTORY" ];then
      error "Pi-Apps download failed!\ngit clone output was: $output"
    fi
  fi
fi #Past this point, DIRECTORY variable populated with valid pi-apps directory

#if chromeOS, install lxterminal
if command -v garcon-terminal-handler >/dev/null ;then
  echo "In order to install apps on chromeOS, a working terminal emulator is required.
Installing lxterminal in 10 seconds... (press Ctrl+C to cancel)"
  sleep 10
  sudo apt install -yf lxterminal || error "Failed to install lxterminal on chromeOS!"
fi

#menu button
if [ ! -f ~/.local/share/applications/pi-apps.desktop ];then
  echo "Creating menu button..."
fi
mkdir -p ~/.local/share/applications
echo "[Desktop Entry]
Name=Pi Apps
Comment=Raspberry Pi App Store for open source projects
Exec=${DIRECTORY}/gui
Icon=${DIRECTORY}/icons/logo.png
Terminal=false
Type=Application
Categories=Utility;
StartupNotify=true" > ~/.local/share/applications/pi-apps.desktop

if [ ! -f ~/.local/share/applications/pi-apps-settings.desktop ];then
  echo "Creating Settings menu button..."
fi
echo "[Desktop Entry]
Name=Pi Apps Settings
Comment=Configure Pi-Apps or create an App
Exec=${DIRECTORY}/settings
Icon=${DIRECTORY}/icons/logo.png
Terminal=false
Type=Application
Categories=Settings;
StartupNotify=true" > ~/.local/share/applications/pi-apps-settings.desktop

if [ ! -f ~/.config/autostart/pi-apps-updater.desktop ];then
  echo "Creating autostarted updater..."
fi
mkdir -p ~/.config/autostart
echo "[Desktop Entry]
Name=Pi Apps Updater
Exec=${DIRECTORY}/updater onboot
Icon=${DIRECTORY}/icons/logo.png
Terminal=false
Type=Application
X-GNOME-Autostart-enabled=true
Hidden=false
NoDisplay=false" > ~/.config/autostart/pi-apps-updater.desktop

mkdir -p "${DIRECTORY}/data" && cd "${DIRECTORY}/data" || error "Failed to make and enter ${DIRECTORY}/data directory!"
mkdir -p installed-packages preload settings status update-status categories
cd $HOME

#hide template app by default
"${DIRECTORY}/etc/categoryedit" "template" 'hidden' >/dev/null

#hide duplicates if running in twisteros
if [ -f /usr/local/bin/twistver ] && [[ $(twistver) == "Twister OS version"* ]]; then
  #twisteros full
  apps="CommanderPi
Box86
Discord
piKiss
Retropie
Scrcpy
Steam
Windows 10 Theme
Chromium Widevine
Lightpad
Wine (x86)
Mac OS Theme"
  PREIFS="$IFS"
  IFS=$'\n'
  for app in $apps ;do
    "${DIRECTORY}/etc/categoryedit" "$app" 'hidden' >/dev/null
  done
  IFS="$PREIFS"
  
elif [ -f /usr/local/bin/twistver ] && [[ $(twistver) != "Twister OS version"* ]]; then
  #twisteros lite
  PREIFS="$IFS"
  IFS=$'\n'
  apps="Chromium Widevine
Box86
Windows 10 Theme
Lightpad
Wine (x86)
Mac OS Theme"
  for app in $apps ;do
    "${DIRECTORY}/etc/categoryedit" "$app" 'hidden' >/dev/null
  done
  IFS="$PREIFS"
  
  #unhide some apps on twisteros lite that were hidden.
  #This removes certain apps completely from the category file. Effectively resets them to online default.
  "${DIRECTORY}/etc/categoryedit" CommanderPi --delete >/dev/null
  "${DIRECTORY}/etc/categoryedit" Discord --delete >/dev/null
  "${DIRECTORY}/etc/categoryedit" piKiss --delete >/dev/null
  "${DIRECTORY}/etc/categoryedit" Scrcpy --delete >/dev/null
  "${DIRECTORY}/etc/categoryedit" Steam --delete >/dev/null
  "${DIRECTORY}/etc/categoryedit" 'Chromium Widevine' --delete >/dev/null
  
  echo "Finished hiding apps on TwisterOS."
fi

#pi-apps terminal command
if [ ! -f /usr/local/bin/pi-apps ] || ! cat /usr/local/bin/pi-apps | grep -q "${DIRECTORY}/gui";then
  echo "#!/bin/bash
${DIRECTORY}/gui"' "$@"' | sudo tee /usr/local/bin/pi-apps >/dev/null
  sudo chmod +x /usr/local/bin/pi-apps
  echo "You can now launch pi-apps from a terminal, just by running 'pi-apps'"
fi

if [ "$(ls "$DIRECTORY/data/settings" 2>/dev/null | wc -l)" -le 2 ];then
  echo "Generating default settings..."
fi
"${DIRECTORY}/settings" refresh

if [ ! -f "$DIRECTORY/data/preload/LIST-" ];then
  echo "Preloading app list..."
fi
"${DIRECTORY}/preload" &>/dev/null

echo "Installation complete."

